const express = require('express');
const fs = require('fs');

const router = express.Router();

const multer = require('multer');
const Excel = require('exceljs');
// 设置存储配置
// const storage = multer.memoryStorage(); // 或者使用磁盘存储 multer.diskStorage// 设置Multer存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/') // 确保这个文件夹存在
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.').pop())
    }
});
const upload = multer({ storage: storage });


router.post('/upload', upload.single('excelFile'), (req, res) => {
    const workbook = new Excel.Workbook(); // 或者使用 XLSX.read(buffer, {type: 'buffer'})
    workbook.xlsx.readFile(req.file.path).then(() => {
        const sheet = workbook.getWorksheet(1); // 获取第一个工作表
        // console.log(req.file, req.body)
        updateJson(sheet, req)
        res.send(`File uploaded and parsed successfully!`);
    }).catch(err => {
        res.status(500).send('Error parsing the Excel file.'+ err);
    });
});
// 更新词库JSON数据
const updateJson = (sheet, req) => {
    const name = req.body.wordName || '';
    let rows = sheet._rows; // 获取所有行数据
    rows = rows.map(el => {
        return {
            id: el.values[1],
            word: el.values[2],
            chinese: el.values[3],
        }
    })
    const jsonData = JSON.stringify(rows, null, 4)
    
    fs.writeFile(`public/jsonData/${req.file.filename}.json`, jsonData, (err) => {
        if (err) {
            console.error(err);
            return;
        }
        updateFilesJson(req, name);
        console.log('File has been created and saved.');
    });
}

const fileListPath = 'public/jsonData/fileList.json'

const updateFilesJson = (req, name) => {
    let filesJson = [] 
    try {
        filesJson = fs.readFileSync(fileListPath, 'utf8')
        filesJson = JSON.parse(filesJson);
    } catch (error) {
        filesJson = []
    }
    let isHas = false
    filesJson.forEach(ele => {
        if (ele.wordName == name || (req.body.id && ele.id == req.body.id)) {
            fs.unlink(`public/jsonData/${ele.fileName}.json`, (err) => {
                if (err) {
                    console.error(err);
                    return;
                }
                ele.fileName = req.file.filename
                console.log('文件删除成功');
            });
            ele.fileName = req.file.filename
            ele.wordName = name
            isHas = true
        }
    })
    if (!isHas) {
        filesJson.push({
            id: Date.now(),
            wordName: name,
            fileName: req.file.filename,
        })
    }
    fs.writeFile(fileListPath, JSON.stringify(filesJson, null, 4), err => {
        if (err) {
            console.error(err);
            return;
        }
        console.log('File has been created and saved.');
    })
}
router.post('/update', (req, res) => {

})
router.post('/fileDelete', (req, res) => {
    const body = req.query || {}
    if (body.id) {
        let filesJson = [] 
        try {
            filesJson = fs.readFileSync(fileListPath, 'utf8')
            filesJson = JSON.parse(filesJson);
        } catch (error) {
            filesJson = []
        }
        let isHas = false
        filesJson.forEach(ele => {
            if (ele.id == body.id) {
                fs.unlink(`public/jsonData/${ele.fileName}.json`, (err) => {
                    if (err) {
                        console.error(err);
                        return;
                    }
                    console.log('文件删除成功');
                });
                isHas  = true
            }
        })
        if (isHas) {
            filesJson = filesJson.filter(ele => ele.id != body.id)
            fs.writeFile(fileListPath, JSON.stringify(filesJson, null, 4), err => {
                if (err) {
                    console.error(err);
                    return;
                }
                console.log('File has been created and saved.');
            })
        }
        
    }
    res.send('successfully')
})
module.exports = router;